#include "ResizeImage.h"

#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
#include <sys/stat.h>
#include <opencv2/opencv.hpp>

using namespace cv;

int main(int argc, char** argv)
{
    if ( argc != 5 )
    {
        printf("usage: ResizeImage.out <Image_Path>\n");
        return -1;
    }


    ResizeImage resizeImage;
    resizeImage.Resize();

    int resizeWidth = atoi(argv[2]);
    int resizeHeight = atoi(argv[3]);
    int isGray = atoi(argv[4]);
    char * src_imgName = argv[1];
    char dst_imgName[1024];
    char * src_imgNameDirIndex = strrchr(src_imgName, '/');
    strncpy(dst_imgName, src_imgName, src_imgNameDirIndex - src_imgName);
    dst_imgName[src_imgNameDirIndex - src_imgName] = '\0';
    if(!isGray)
        sprintf(dst_imgName, "%s/%dx%d_normal", dst_imgName, resizeWidth, resizeHeight);
    else
        sprintf(dst_imgName, "%s/%dx%d_gray", dst_imgName, resizeWidth, resizeHeight);
    mkdir(dst_imgName, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    sprintf(dst_imgName, "%s/%s",dst_imgName, src_imgNameDirIndex + 1);
    printf("src image%s\n", argv[1]);
    printf("dst image:%s\n", dst_imgName);
    Mat src_img = imread(src_imgName, CV_LOAD_IMAGE_COLOR);
    Mat dst_img(resizeWidth,resizeHeight,src_img.type());
    resize(src_img,dst_img,dst_img.size(),0,0,INTER_LINEAR);
    
    Mat dst_img_gray;  
    cvtColor(dst_img,dst_img_gray,CV_BGR2GRAY);
    if(!isGray)
      imwrite(dst_imgName, dst_img);
    else
    {
        //imwrite(dst_imgName, dst_img_gray);
        //return 0;
        printf("dst_img_gray's channels:%d continous:%d\n", dst_img_gray.channels(), dst_img_gray.isContinuous());
        FILE * fp = fopen(dst_imgName, "wb");
        //FILE * fp = fopen(dst_imgName, "ab");
        if(fp != NULL)
        {
            /*
            for(int i = 0; i < resizeWidth; ++i)
            {
                uchar* data = dst_img_gray.ptr<uchar>(i);
                for(int j = 0; j < resizeHeight; ++j)
                {
                    fwrite(&data[j], sizeof(char), 1, fp);
                }
            }
            */
            fwrite(dst_img_gray.data, sizeof(char), resizeWidth*resizeHeight, fp);
            fclose(fp);
        }
    }

    return 0;
}
